<?php

namespace AdminBundle\Controller;

use AdminBundle\Entity\TaskJobs;
use AdminBundle\Entity\TaskJobSteps;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;
use AdminBundle\Utility\Constant;
use Symfony\Component\Validator\Constraints\DateTime;

/**
 * Taskjob controller.
 *
 * @Route("taskjobs")
 */
class TaskJobsController extends Controller
{
    /**
     * Lists all taskJob entities.
     *
     * @Route("/", name="taskjobs_index")
     * @Method("GET")
     */
    public function indexAction(Request $request)
    {
        $page = $request->get("page");
        $page = is_numeric($page) ? $page : 1;
        $keyword = $request->get('keyword');
        $date_range = $request->get('date_range');
        $device_group = $request->get('device_group');
        if (!empty($date_range)) {
            $date_range = explode(" - ", $date_range);
            $starttime = $date_range[0];
            $endtime = $date_range[1];
        } else {
            $starttime = $endtime = null;
        }

        $starttime = date("Y-m-d", strtotime($starttime ?: "-3 day"));
        $endtime = date("Y-m-d", strtotime($endtime ?: "+1 day"));

        $params = ['keyword' => $keyword, 'starttime' => $starttime, 'endtime' => $endtime,
            'device_group' => $device_group, 'freq_type' => Constant::FREQ_TYPE];


        $em = $this->getDoctrine()->getManager();
        if ($device_group) {
            $result = $em->getRepository('AdminBundle:TaskJobs')->pageQuery($params, $page);
        } else {
            $result = $em->getRepository('AdminBundle:TaskJobs')->pageTemplate($page);
        }

        $baseGroup = $em->getRepository('AdminBundle:BaseGroup')->findAll();
        $params['baseGroups'] = $baseGroup;

        return $this->render('AdminBundle:taskjobs:index.html.twig', array_merge([
            'dataSources' => $result['list'],
            'querystring' => http_build_query($params),
            'page' => $result['page'],
        ], $params));
    }

    /**
     * Creates a new taskJob or edit entity.
     *
     * @Route("/job", name="taskjobs_job")
     * @Method({"GET", "POST"})
     */
    public function jobAction(Request $request)
    {
        $data_template = [
            'packageName' => '', 'packageId' => 0, 'groupId' => 0,
            'freqType' => '1', 'freqExpression' => '* * * * * * ',
            'activeStartDate' => '0000-00-00', 'activeEndDate' => '9999-12-31',
            'activeStartTime' => '00:00:00', 'activeEndTime' => '23:59:59', 'isEnabled' => 0];
        foreach ($data_template as $name => $value) {
            $data_template[$name] = $request->request->get($name, $value);
        }
        $em = $this->getDoctrine()->getManager();
        $taskJobs = $em->getRepository('AdminBundle:TaskJobs')->findOneBy([
            'packageId' => $data_template['packageId'],
            'groupId' => $data_template['groupId']
        ]);

        if ($taskJobs == null) {
            $taskJobs = new TaskJobs();
            $taskJobs->setIp($request->getClientIp())
                ->setCreator($this->getUser()->getUsername());
        }
        $activeStartTime = new \DateTime();
        $activeStartTime->setTimestamp(strtotime($data_template['activeStartTime']));
        $activeEndTime = new \DateTime();
        $activeEndTime->setTimestamp(strtotime($data_template['activeEndTime']));

        $taskJobs->setCtime(new \DateTime())
            ->setIsEnabled($data_template['isEnabled'])
            ->setName($data_template['packageName'])
            ->setPackageId($data_template['packageId'])
            ->setGroupId($data_template['groupId'])
            ->setFreqType($data_template['freqType'])
            ->setFreqExpression($data_template['freqExpression'])
            ->setActiveStartDate(date_create($data_template['activeStartDate']))
            ->setActiveEndDate(date_create($data_template['activeEndDate']))
            ->setActiveStartTime($activeStartTime)
            ->setActiveEndTime($activeEndTime);

        $em->persist($taskJobs);
        $em->flush();

        return $this->json(['id' => $taskJobs->getId()]);
    }

    /**
     * get template by id of taskJob entity .
     *
     * @Route("/job/{id}/template", name="taskjobs_template")
     * @Method({"GET", "POST"})
     */
    public function templateAction(Request $request, $id)
    {
        $params = ['job_id' => $id];
        $page = $request->query->get('page', 1);
        $result = $this->getDoctrine()->getManager()->getRepository('AdminBundle:TaskJobs')->templateByJob($params, $page);
        $jqgrid_format = [
            'page' => $page,
            'total' => 1,
            'records' => $result['page']['rows'],
            'rows' => $result['list'],
        ];
        return $this->json($jqgrid_format);
    }

    /**
     * create or edit jobStep of template by id of taskJob entity .
     *
     * @Route("/job/{id}/step", name="taskjobs_template_step_edit")
     * @Method({"GET", "POST"})
     */
    public function jobStepAction(Request $request, $id)
    {
        $result = ['job_id' => 0];

        $data_template = ['jobId' => $id, 'id' => 0, 'name' => '', 'isEnabled' => 0, 'isRand' => 0, 'recurrenceFactor' => 1, 'oper' => 'edit'];
        foreach ($data_template as $name => $value) {
            $data_template[$name] = $request->request->get($name, $value);
        }
        if (empty($data_template['id'])) {
            return $this->json($result);
        }
        $em = $this->getDoctrine()->getManager();
        $taskJobStep = $em->getRepository('AdminBundle:TaskJobSteps')->findOneBy([
            'jobId' => $data_template['jobId'],
            'templateId' => $data_template['id']
        ]);

        if ($taskJobStep == null) {
            $taskJobStep = new TaskJobSteps();
            $taskJobStep->setCtime(new \DateTime())
                ->setIp($request->getClientIp())
                ->setCreator($this->getUser()->getUsername())
                ->setJobId($data_template['jobId'])
                ->setTemplateId($data_template['id']);
        }
        $taskJobStep->setName($data_template['name'])
            ->setIsEnabled($data_template['isEnabled'])
            ->setStepId($data_template['id'])
            ->setIsRand($data_template['isRand'])
            ->setRecurrenceFactor($data_template['recurrenceFactor']);

        $em->persist($taskJobStep);
        $em->flush();

        $result = ['job_id' => $taskJobStep->getId()];
        return $this->json($result);
    }

    /**
     * Creates a new taskJob entity.
     *
     * @Route("/new", name="taskjobs_new")
     * @Method({"GET", "POST"})
     */
    public function newAction(Request $request)
    {
        $taskJob = new Taskjob();
        $form = $this->createForm('AdminBundle\Form\TaskJobsType', $taskJob, Constant::FORM_ATTR_CLASS);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($taskJob);
            $em->flush();

            return $this->redirectToRoute('taskjobs_show', array('id' => $taskJob->getId()));
        }

        return $this->render('AdminBundle:taskjobs:new.html.twig', array(
            'taskJob' => $taskJob,
            'form' => $form->createView(),
        ));
    }

    /**
     * Finds and displays a taskJob entity.
     *
     * @Route("/{id}", name="taskjobs_show")
     * @Method("GET")
     */
    public function showAction(TaskJobs $taskJob)
    {
        $deleteForm = $this->createDeleteForm($taskJob);

        return $this->render('taskjobs/show.html.twig', array(
            'dataSource' => $taskJob,
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Displays a form to edit an existing taskJob entity.
     *
     * @Route("/{id}/edit", name="taskjobs_edit")
     * @Method({"GET", "POST"})
     */
    public function editAction(Request $request, TaskJobs $taskJob)
    {
        $deleteForm = $this->createDeleteForm($taskJob);
        $editForm = $this->createForm('AdminBundle\Form\TaskJobsType', $taskJob, Constant::FORM_ATTR_CLASS);
        $editForm->handleRequest($request);

        if ($editForm->isSubmitted() && $editForm->isValid()) {
            $this->getDoctrine()->getManager()->flush();

            return $this->redirectToRoute('taskjobs_edit', array('id' => $taskJob->getId()));
        }

        return $this->render('AdminBundle:taskjobs:edit.html.twig', array(
            'dataSource' => $taskJob,
            'form' => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Deletes a taskJob entity.
     *
     * @Route("/{id}", name="taskjobs_delete")
     * @Method("DELETE")
     */
    public function deleteAction(Request $request, TaskJobs $taskJob)
    {
        $form = $this->createDeleteForm($taskJob);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->remove($taskJob);
            $em->flush();
        }

        return $this->redirectToRoute('taskjobs_index');
    }

    /**
     * Creates a form to delete a taskJob entity.
     *
     * @param TaskJobs $taskJob The taskJob entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm(TaskJobs $taskJob)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('taskjobs_delete', array('id' => $taskJob->getId())))
            ->setMethod('DELETE')
            ->getForm();
    }
}
